﻿let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
let signCode = "slel3@lsl334xx,deka";
let Cio = require('socket.io-client');
let log = require("./../util/loginfo").getInstand;
let gameInfo = require('./class/game').getInstand;
let gameConfig = require('./config/gameConfig');
let Csocket = Cio('http://localhost:13000');

let lock = require('async-lock');
let lotteryLock = new lock(); //下注专用锁

Csocket.on('disconnect', function (data) {
	log.info("登录服务器被断开 " + data);
});

Csocket.on('connected', function (msg) {
	log.info("与登录服务器进行连接...... " + msg);
	var info = { serverName: "百人场_1006_马上发财", serverId: gameConfig.serverId, signCode: "slel3@lsl334xx,deka" };
	Csocket.emit('GameServerConnect', info)
});

Csocket.on('GameServerConnectResult', function (msg) {
	if (msg && msg.resultCode) {
		log.info("连接成功 " + msg);
	}
});


Csocket.on('LoginGameResult', function (msg) {
	try {
		if (!msg) {
			return;
		}
		log.info(".登录百人场_1006_马上发财服务器回应" + JSON.stringify(msg));
		if (msg.ResultCode) {
			gameInfo.updateUser(msg.userInfo);
		} else {
			gameInfo.sendLoginGameFailed(msg.userid, msg.msg);
		}
	} catch (error) {
		log.err(error);
	}
});

Csocket.on('addgold', function (msg) {
	try {
		if (!msg) {
			return;
		}
		var result = gameInfo.addgold(msg.userid, msg.addgold);
		Csocket.emit('addgoldResult', { Result: result });

		//当前用户桌子广播
		var User = gameInfo.getUser(msg.userid);
		if (User) {
			var tablestring = "table" + User.getTable();
			io.sockets.in(tablestring).emit('userGoldUpdate', { userId: msg.userid, updateSocre: User.getScore() });
		}
	} catch (error) {
		log.err(error);
	}
});

Csocket.on('getgold', function (msg) {
	try {
		if (!msg) {
			return;
		}
		var score = gameInfo.getPlayerScore(msg.userid);
		Csocket.emit('getgoldResult', { Result: 1, score: score });
	} catch (error) {
		log.err(error);
	}
});

Csocket.on('disconnectUser', function (msg) {
    try {
        var list = gameInfo.getOnlinePlayer();
        if (list[msg.userId]) {
	// kicked, ZZZ-20230509
		list[msg.userId]._socket.emit(msg.sysCommand, msg);
            list[msg.userId]._socket.disconnect();
        } else {
            log.err(msg.userId + " 用户不存在");
            var result = {ResultCode: 0, userId: msg.userId};
            Csocket.emit("userDisconnect", result);
        }
    } catch (error) {
        log.err(error);
    }
});


Csocket.on('applyMatchResult', function (_info) {
	try {
		//log.info(_info);
		gameInfo.addRankUserList(_info);
		//gameInfo.fishShoot(socket,fishShootInfo);
	} catch (error) {
		log.err(error);
	}
});

Csocket.on('Setmaintain', function () {
	try {
		gameInfo.Setmaintain();
	} catch (error) {
		log.err(error);
	}
});

gameInfo.setIo(io, Csocket);

io.on('connection', function (socket) {

	socket.emit('connected', 'connect game server');

	//客户登录游戏
	socket.on('LoginGame', function (GameInfo) {
		try {
			var data = JSON.parse(GameInfo);
			GameInfo = data;
		} catch (e) {
			log.warn('LoginGame-json');
		}

		//是不是维护模式
		if (gameInfo.isMaintain()) {
			log.info("维护模式,禁止登录!");
			socket.emit("maintain", { ResultCode: 1, msg: true });
			return;
		}

		if (!GameInfo) {
			log.err("登录游戏,参数不正确!");
			return;
		}

		if (!GameInfo.sign) {
			log.err("签名为空!");
			return;
		}

		if (!gameInfo.getUser(GameInfo.userid)) {
			gameInfo.addUser(GameInfo, socket);
			var msg = {
				userid: GameInfo.userid,
				sign: GameInfo.sign,
				gameId: gameInfo.serverId,
				serverSign: signCode,
				serverId: gameConfig.serverId
			};
			Csocket.emit('LoginGame', msg);
			log.info("user " + GameInfo.userid + " login game!");
		} else {
			log.warn("用户已经在服务器了，无需重复登录");
		}
	});

	//然后再登录房间
	socket.on('LoginRoom', function (RoomInfo) {
		try {
			var data = JSON.parse(RoomInfo);
			RoomInfo = data;
		} catch (e) {
			log.warn('LoginRoom-json');
		}
		//如果没有房间概念，就默认为1
		//这还应该检测是否进入了游戏，如果没有需要先进入
		//log.info("进入房间")
		try {
			gameInfo.LoginRoom(socket.userId, RoomInfo.roomid, socket);
		} catch (error) {
			log.err(error);
		}
	});


	//离开房间
	socket.on('LogoutRoom', function () {
		try {
			gameInfo.LogoutRoom(socket);
		} catch (error) {
			log.err(error);
		}
	});

	socket.on("getMark", function (_info) {
		try {
			var data = JSON.parse(_info);
			_info = data;
		} catch (e) {
			log.warn('getmark-json error');
		}
		gameInfo.getMark(_info, Csocket);
	});

	//下注
	socket.on('lottery', function (lottery) {
		lotteryLock.acquire('lottery', async () => {
			if (!socket.userId) {
				log.err("没有用户id " + socket.userId);
				return;
			}
			try {
				log.info("lottery " + lottery);
				var data = JSON.parse(lottery);
				lottery = data;

				gameInfo.lottery(socket.userId, lottery, function (state) {
					if (state < 1) {
						socket.emit('lotteryResult', { ResultCode: state });
					} else {
						socket.emit('lotteryResult', { ResultCode: state });
					}
				});
			} catch (error) {
				log.err("lottery error " + error);
			}
		});
	});

	//获取历史游戏记录
	socket.on('getGameRecord', function () {
		try {
			gameInfo.selectRecord(socket);
		} catch (error) {
			log.err(error);
		}
	});


	//离线操作
	socket.on('disconnect', function () {

		try {
			if (!socket.userId) {
				return;
			}
			//通知登录服务器，已经下线存储游戏数据
			//log.info(socket.userId)
			var userInfo = gameInfo.getUser(socket.userId);
			if (userInfo) {
				if (userInfo.Islogin()) {
					//if (gameInfo.game_type == 4) { //游戏是否结束
					//log.info("离线游戏结束清理玩家数据 玩家ID ", socket.userId);
					gameInfo.deleteUser(socket);
					//}
					var result = {
						ResultCode: 1,
						userId: userInfo._userId,
						userScore: userInfo._score,
						gameId: gameConfig.serverId,
						nolog: true
					};
					Csocket.emit("userDisconnect", result);
					//断线存储相应数据(在新的数据库里存储,消耗子弹与收获金币)
					socket.userId = null;
				} else {
					userInfo._isLeave = true;
					log.warn('未更新用户数据离开');
				}
			} else {
				log.info("用户未登录离开!")
			}
		} catch (error) {
			log.err("disconnect error " + error);
		}
	});
});

app.set('port', process.env.PORT || gameConfig.port);

var server = http.listen(app.get('port'), function () {
	log.info('start at port:' + server.address().port);
});

log.info("百人场_1006_马上发财服务器启动");

